import { viewBaseInfo } from '@/services/product/productManufactInforExecute';
import { addBomReview, delBomReviewByIds } from '@/services/design/bomReview';
import { Ellipsis } from '@/components/Ellipsis';
import {
  PlusOutlined,
  UploadOutlined,
  ArrowLeftOutlined,
  DownloadOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import '@/pages/design/style.less';
import ProTable from '@ant-design/pro-table';
import {
  Button,
  Form,
  Input,
  message,
  Modal,
  Upload,
  InputNumber,
  Row,
  Col,
  Select,
  Card,
  Tabs,
  notification,
  Tooltip,
} from 'antd';
import { sortTran, filterTran, filterTranNew } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import { history } from 'umi';
import {
  delStandFileInfo,
  downloadFile,
  getDrawingTypeList,
  getPreviewUrl,
  getStandFileInfoByStandTypeIdAndCategoryPage,
  switchStandFileInfo,
  uploadStandFileInfoBom,
  uploadStandFileInfoDrawing,
} from '@/services/design/standFileInfo';
import { log } from '@antv/g2plot/lib/utils';
import { downloadStandardBom } from '@/services/design/productBomOverview';
import { getProductBomOverviewOfStandProduct } from '@/services/design/standProductBomDesign';
const StandProductFileInfo: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const ref = useRef(null);
  const [modalVisit, setModalVisit] = useState(false); // 图纸上传modal
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState(''); //bom、图纸上传modal标题
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [modalVisit2, setModalVisit2] = useState(false); //bom上传modal
  const [confirmLoading2, setConfirmLoading2] = useState(false);
  const [createOrUpdate2, setCreateOrUpdate2] = useState(false); //编辑框的disable
  const [file, setFile] = useState();
  const [form] = Form.useForm();
  const [form1] = Form.useForm();
  const [inputValue, setInputValue] = useState(0); //记录下编辑的数量
  const [selectedDrawingRows, setSelectedDrawingRows] = useState([]); //图纸列表勾选项
  const [optionsstandfile, setoptionsstandfile] = useState([]); //图纸类型
  const [standProductRecord, setStandProductRecord] = useState(null);
  const bomOption = [{ label: 'BOM', value: 'BOM' }]; //BOM下拉框
  type DataSourceType = {
    id: React.Key;
    title?: string;
    readonly?: string;
    decs?: string;
    state?: string;
    created_at?: number;
    update_at?: number;
    children?: DataSourceType[];
  };

  /**
   * @description: 初始化标准柜体信息
   * @return {*}
   */
  useEffect(() => {
    try {
      console.log('路径信息：', history.location.state.record);
      const { record } = history.location.state;
      if (!record) {
        throw new Error('获取标准柜体信息失败！');
      }
      setStandProductRecord(record);
      getproductInfo();
    } catch (error) {
      notification.error({
        message: error.message,
      });
    }
  }, []);

  /* columns配置 */
  const bomColumns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
      hideInTable: true,
    },
    {
      title: 'BOM编号',
      dataIndex: 'bomCode',
      width: 200,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    // {
    //   title: '版本',
    //   dataIndex: 'version',
    //   align: 'center',
    //   sorter: true,

    //   width: 80,
    //   render: (text) => <>{Ellipsis(text)}</>,
    // },
    {
      title: '物料编号',
      dataIndex: 'materialCode',
      width: 150,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '物料名称',
      dataIndex: 'materialName',
      width: 130,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '物料规格',
      dataIndex: 'materialSpec',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
      width: 140,
    },
    {
      title: '数量',
      dataIndex: 'materialQty',
      width: 80,
      align: 'center',
      sorter: true,
      valueType: 'digit',
      render: (text) => <>{Ellipsis(text)}</>,
      editable: (text, record, index) => {
        return true;
      },
      renderFormItem: ({ index }) => {
        return <InputNumber type="number" precision={0} min={0} placeholder="请输入正整数" />;
      },
    },
    {
      title: '单位',
      dataIndex: 'unit',
      width: 80,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '位置号',
      dataIndex: 'positionNo',
      width: 100,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '物料品牌',
      dataIndex: 'brand',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
      width: 140,
    },
    {
      title: '物料分类',
      dataIndex: 'materialClassification',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
      width: 140,
    },
    {
      title: '物料种类',
      dataIndex: 'materialType',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
      width: 140,
    },
    {
      title: '是否甲供料',
      dataIndex: 'isJia',
      width: 100,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
  ];
  const drawingColumns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 60,
      align: 'center',
      sorter: true,
    },
    {
      title: '文件类别',
      dataIndex: 'category',
      width: 100,
      align: 'center',
      sorter: true,
      ellipsis: true,
    },
    {
      title: '文件编号',
      dataIndex: 'fileCode',
      width: 200,

      align: 'center',
      sorter: true,
    },
    {
      title: '文件名称',
      dataIndex: 'fileName',
      width: 200,
      ellipsis: true,

      align: 'center',
      sorter: true,
    },
    {
      title: '版本号',
      dataIndex: 'version',
      render: (text) => {
        return <div>{text}</div>;
      },
      width: 80,
      align: 'center',
      sorter: true,
    },
    {
      title: '启用状态',
      dataIndex: 'status',
      render: (text) => {
        return <div>{text === 1 ? '是' : '否'}</div>;
      },
      width: 80,

      align: 'center',
      sorter: true,
    },
    {
      title: '上传人', //表头显示的名称
      search: false,
      dataIndex: 'createName',
      width: 100,
      align: 'center',
      sorter: true,
    },
    {
      title: '上传日期', //表头显示的名称
      search: false,
      dataIndex: 'createTime',
      width: 100,

      align: 'center',
      sorter: true,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      width: 160,
      align: 'center',
      render: (text, record, _, action) => [
        <a
          key="downloadKey"
          onClick={async () => {
            if (
              record.fileExtEndDate == 'pdf' ||
              record.fileExtEndDate == 'png' ||
              record.fileExtEndDate == 'jpg'
            ) {
              const url = await getPreviewUrl(record);
              const w = window.open('about:blank');
              w.location.href = url.message;
            } else {
              downloadFile({ standFileId: record.id }).then((res) => {
                const aLink = document.createElement('a');
                document.body.appendChild(aLink);
                aLink.style.display = 'none';
                aLink.href = window.URL.createObjectURL(res);
                aLink.setAttribute('download', `${record.fileName}`);
                aLink.click();
                document.body.removeChild(aLink);
              });
            }
          }}
        >
          预览下载
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delStandFileInfo({ id: record.id });
                actionRef.current?.reload();
              },
            });
          }}
        >
          删除
        </a>,
        <a
          key="useKey"
          onClick={async () => {
            if (record.status == '1') {
              message.warning('当前图纸已启用');
            }
            if (record.status == '-1') {
              const fileinfoparams = {
                category: record.category,
                standFileInfoId: record.id,
                standTypeId: record.standTypeId,
                status: '1',
              };
              console.log(fileinfoparams);
              const result = await switchStandFileInfo(fileinfoparams);
              if (result != null) {
                message.success('启用成功');
                actionRef.current?.reload();
              }
            }
          }}
        >
          启用
        </a>,
        <a
          key="nonuseKey"
          onClick={async () => {
            if (record.status == '-1') {
              message.warning('当前图纸已禁用');
            }
            if (record.status == '1') {
              const fileinfoparams = {
                category: record.category,
                standFileInfoId: record.id,
                standTypeId: record.standTypeId,
                status: '-1',
              };
              console.log(fileinfoparams);
              const result = await switchStandFileInfo(fileinfoparams);
              if (result != null) {
                message.success('禁用成功');
                actionRef.current?.reload();
              }
            }
          }}
        >
          禁用
        </a>,
      ],
    },
  ];
  /*
   * method
   * @description: 提交图纸和bom附件，根据formTitle复用上传
   * @return {null}
   */
  const handleSubmit = async () => {
    setConfirmLoading(true);
    if (formTitle == '上传BOM附件') {
      form1
        .validateFields()
        .then(async () => {
          const res = {
            ...form1.getFieldsValue(),
            standTypeCode: standProductRecord.standTypeCode,
            standTypeDesc: standProductRecord.standTypeDesc,
            standTypeId: standProductRecord.id,
            standTypeName: standProductRecord.standTypeName,
          };
          const formData = new window.FormData();
          res.file.fileList.map((file: any) => {
            formData.append('file', file.originFileObj);
          });
          res.file = formData;
          res.category = 'BOM';
          console.log(res);
          const result = await uploadStandFileInfoBom(res);
          console.log('bom上传结果：', result);

          if (result != null) {
            message.success('添加成功');
            form1.resetFields();
          }
          setConfirmLoading2(false);
          setModalVisit2(false);
          actionRef.current?.reload();
        })
        .catch(() => {
          setConfirmLoading2(false);
        });
    }
    if (formTitle == '上传图纸附件') {
      form
        .validateFields()
        .then(async () => {
          const res = {
            ...form.getFieldsValue(),
            standTypeCode: standProductRecord.standTypeCode,
            standTypeDesc: standProductRecord.standTypeDesc,
            standTypeId: standProductRecord.id,
            standTypeName: standProductRecord.standTypeName,
          };
          console.log('附件信息：', res.file.fileList);
          const formData = new window.FormData();
          res.file.fileList.map((file: any) => {
            formData.append('file', file.originFileObj);
          });
          res.file = formData;
          const result = await uploadStandFileInfoDrawing(res);
          if (result != null) {
            message.success('添加成功');
            form.resetFields();
          }
          setConfirmLoading(false);
          setModalVisit(false);
          actionRef.current?.reload();
        })
        .catch(() => {
          console.log('提交失败');
          setConfirmLoading(false);
        });
    }
  };
  /**
   * @description: 获取图纸类型
   * @return {null}
   */
  const getproductInfo = () => {
    //柜体类型
    getDrawingTypeList(null)
      .then((res) => {
        const gettype = res;
        if (!gettype) {
          throw new Error('获取标准柜体类型失败！');
        }
        const productfiletype: any[] = [];
        gettype.data.map((item: any, index: any) => {
          productfiletype.push({ value: item, label: item });
        });
        console.log('柜体类型信息：', productfiletype);
        setoptionsstandfile(productfiletype);
      })
      .catch((error) => {
        notification.error({
          message: error.message,
        });
      });
  };
  /**
   * @description: 修改upload上传验证，取消upload默认行为和上传进度条
   * @return {false}
   */
  const handleBeforeUpload = (info: any) => {
    return false;
  };

  /**
   * @description: 选中项目，导出工时模板
   * @return {*}
   */
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: string[]) => {
      const temp = [];
      if (selectedRows !== null) {
        selectedRows.map((item) => {
          temp.push(item);
        });
      }
      setSelectedDrawingRows(temp); //保存项目信息
    },
  };

  //定义Tabs的子结构的数组
  const standProductFileInfoTabList: tabType[] = [
    {
      name: 'tab1',
      label: 'BOM清单',
      content: (
        <>
          <ProTable
            headerTitle="BOM清单查询"
            actionRef={actionRef}
            columns={bomColumns}
            rowKey="id"
            search={false}
            toolBarRender={(action, { selectedRows }) => [
              <Button
                key="button"
                icon={<ArrowLeftOutlined />}
                onClick={() => {
                  history.push('/design/standProduct');
                }}
                type="primary"
              >
                返回
              </Button>,
              <Button
                key="download"
                icon={<DownloadOutlined />}
                onClick={() => {
                  downloadStandardBom(null).then((res) => {
                    const aLink = document.createElement('a');
                    document.body.appendChild(aLink);
                    aLink.style.display = 'none';
                    aLink.href = window.URL.createObjectURL(res);
                    aLink.setAttribute('download', `BOM导入模板.xls`);
                    aLink.click();
                    document.body.removeChild(aLink);
                  });
                }}
                type="primary"
              >
                下载BOM模板
              </Button>,
              <Button
                key="upload"
                icon={<UploadOutlined />}
                onClick={() => {
                  setCreateOrUpdate2(true);
                  setFormTitle('上传BOM附件');
                  setModalVisit2(true);
                }}
                type="primary"
              >
                上传BOM
              </Button>,
            ]}
            request={async (params, sort, filter) => {
              const sorters = sortTran(sort);
              const filters = filterTranNew(params);
              const pageEntity = {
                current: params.current,
                filters: filters,
                pageSize: params.pageSize,
                sorters: sorters,
              };
              const result = await getProductBomOverviewOfStandProduct({
                pageEntity: pageEntity,
                standTypeId: standProductRecord?.id,
              });
              console.log('查询结果：', result.data.content);
              return {
                data: result.data.content,
                success: result.message,
                total: result.data.totalElements,
              };
            }}
            scroll={{ x: 2000, y: 400 }}
            rowSelection={{}}
            revalidateOnFocus={true}
          />
        </>
      ),
    },
    {
      name: 'tab2',
      label: '图纸列表',
      content: (
        <>
          <ProTable
            headerTitle="标准柜体图纸列表"
            scroll={{ x: 1500, y: 300 }}
            actionRef={actionRef} //用于触发刷新操作等，看api
            rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
            formRef={ref}
            search={false}
            toolBarRender={(action, { selectedRows }) => [
              // eslint-disable-next-line react/jsx-key
              <div className="standFileInfoTooltipStyle">
                <ExclamationCircleOutlined />
                <span>上传须知：需要上传并启用“电气原理图”和“箱柜接线表”</span>
              </div>,
              <Button
                key="button"
                icon={<ArrowLeftOutlined />}
                onClick={() => {
                  history.push('/design/standProduct');
                }}
                type="primary"
              >
                返回
              </Button>,
              <Button
                key="button"
                icon={<UploadOutlined />}
                onClick={() => {
                  setCreateOrUpdate(true);
                  setFormTitle('上传图纸附件');
                  setModalVisit(true);
                }}
                type="primary"
              >
                上传图纸
              </Button>,
            ]}
            request={async (params = {}, sort, filter) => {
              const res = { ...params };
              const sorters = sortTran(sort);
              const filters = filterTranNew(res);
              const drawingparams = {
                category: '图纸',
                pageEntity: {
                  current: 1,
                  filters: filters,
                  pageSize: 6,
                  sorters: sorters,
                },
                standTypeId: standProductRecord.id,
              };
              const result = await getStandFileInfoByStandTypeIdAndCategoryPage(drawingparams);
              //日期处理，只保留日期的年月日部分
              result.data.content.map((item: any) => {
                item.createTime = item.createTime.split(' ')[0];
              });

              return {
                data: result.data.content,
                total: result.data.totalElements,
                success: result.success,
              };
            }}
            columns={drawingColumns}
            rowSelection={{ selectedDrawingRows, ...rowSelection }}
          />
        </>
      ),
    },
  ];

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <Tabs
        destroyInactiveTabPane
        type="card"
        animated={true}
        style={{ background: 'white' }}
        items={standProductFileInfoTabList.map((item, i) => {
          const id = String(i + 1);
          return {
            label: item.label,
            key: id,
            children: <div>{item.content}</div>,
          };
        })}
      />
      <Modal
        title={formTitle}
        visible={modalVisit}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => {
          setModalVisit(false);
          form.resetFields();
        }}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
          initialValues={{
            category: '电气原理图',
          }}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            label="文件类别"
            name="category"
            rules={[{ required: true, message: '请选择文件类别!' }]}
          >
            <Select placeholder="请选择文件类别" options={optionsstandfile} />
          </Form.Item>
          <Form.Item
            label="上传文件"
            name="file"
            rules={[{ required: true, message: '请上传文件!' }]}
          >
            <Upload
              file-list="file"
              //   customRequest={onFilesChange} //通过覆盖默认的上传行为，可以自定义自己的上传实现
              showUploadList={true}
              beforeUpload={handleBeforeUpload}
              multiple
            >
              <Button className="standProduct_UploadStyle" icon={<UploadOutlined />}>
                上传文件
              </Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title={formTitle}
        visible={modalVisit2}
        onOk={handleSubmit}
        confirmLoading={confirmLoading2}
        onCancel={() => {
          setModalVisit2(false);
          form1.resetFields();
        }}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form1}
          wrapperCol={{ flex: 1 }}
          colon={false}
          initialValues={{ category: 'BOM' }}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          {/* <Row justify={'space-between'}>
            <Col span={14}>
              <Form.Item
                label="文件类别"
                name="category"
                rules={[{ required: true, message: '请选择文件类别!' }]}
              >
                <Select defaultValue="BOM" options={bomOption} />
              </Form.Item>
            </Col>
            <Col>
              <Button
                key="bombutton"
                icon={<DownloadOutlined />}
                onClick={() => {
                  downloadStandardBom(null).then((res) => {
                    const aLink = document.createElement('a');
                    document.body.appendChild(aLink);
                    aLink.style.display = 'none';
                    aLink.href = window.URL.createObjectURL(res);
                    aLink.setAttribute('download', `BOM导入模板.xls`);
                    aLink.click();
                    document.body.removeChild(aLink);
                  });
                }}
                type="primary"
              >
                下载BOM模板
              </Button>
            </Col>
          </Row> */}
          <Form.Item
            label="上传文件"
            name="file"
            rules={[{ required: true, message: '请上传文件!' }]}
          >
            {/* <div key={Math.random()}> */}
            <Upload
              file-list="fileList"
              //   customRequest={onFilesChange} //通过覆盖默认的上传行为，可以自定义自己的上传实现
              showUploadList={true}
              beforeUpload={handleBeforeUpload}
              multiple={true}
            >
              <Button className="standProduct_UploadStyle" icon={<UploadOutlined />}>
                上传文件
              </Button>
            </Upload>
            {/* </div> */}
          </Form.Item>
          {/* <Form.Item label="备注" name="memo">
            <Input />
          </Form.Item> */}
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default StandProductFileInfo;
